package com.itheima.stock.service.Impl;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.itheima.stock.common.StockInfoConfig;
import com.itheima.stock.common.domain.*;
import com.itheima.stock.mapper.StockBlockRtInfoMapper;
import com.itheima.stock.mapper.StockBusinessMapper;
import com.itheima.stock.mapper.StockMarketIndexInfoMapper;
import com.itheima.stock.mapper.StockRtInfoMapper;
import com.itheima.stock.pojo.StockBusiness;
import com.itheima.stock.service.StockService;
import com.itheima.stock.utils.DateTimeUtil;
import com.itheima.stock.vo.resp.R;
import com.itheima.stock.vo.resp.ResponseCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.joda.time.DateTime;
import org.joda.time.DateTimeField;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class StockServiceImpl implements StockService {
    @Autowired
    private StockBusinessMapper stockBusinessMapper;
    @Autowired
    private StockInfoConfig stockInfoConfig;
    @Autowired
    private StockMarketIndexInfoMapper stockMarketIndexInfoMapper;
    @Autowired
    private StockBlockRtInfoMapper stockBlockRtInfoMapper;
    @Autowired
    private StockRtInfoMapper stockRtInfoMapper;


    @Override
    public R<List<StockBusiness>> findAllBusiness() {
        List<StockBusiness> list = stockBusinessMapper.findAll();
        return R.ok(list);
    }

    @Override
    public R<List<InnerMarketDomain>> innerIndexAll() {
        List<String> inner = stockInfoConfig.getInner();
        String lastdata = DateTimeUtil.getLastDateString4Stock(DateTime.now());
        lastdata = "20211226105600";
        List<InnerMarketDomain> map = stockMarketIndexInfoMapper.selectByIdsAndDate(inner, lastdata);
        if (CollectionUtils.isEmpty(map)) {
            return R.error(ResponseCode.TOKEN_NO_AVAIL.getMessage());
        }
        return R.ok(map);
    }

    @Override
    public R<List<PlateMarketDomain>> sectorAll() {
        List<PlateMarketDomain> plateMarketDomains = stockBlockRtInfoMapper.sectorAll();
        if (CollectionUtils.isEmpty(plateMarketDomains)) {
            return R.error(ResponseCode.SYSTEM_ERROR.getMessage());
        }
        return R.ok(plateMarketDomains);
    }

    @Override
    public R<List<InnerMarketDomain>> getStockIncrease() {
        List<InnerMarketDomain> innerMarketDomains = stockRtInfoMapper.getStockIncrease();
        if (CollectionUtils.isEmpty(innerMarketDomains)) {
            return R.error(ResponseCode.SYSTEM_ERROR.getMessage());
        }

        return R.ok(innerMarketDomains);
    }

    @Override
    public R<PageResult> getStockAll(Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        //查询
        List<InnerMarketDomain> maps = this.stockRtInfoMapper.getStockAll();
        if (CollectionUtils.isEmpty(maps)) {
            return R.error("暂无数据");
        }
        PageInfo<InnerMarketDomain> pageInfo = new PageInfo<>(maps);
        PageResult<InnerMarketDomain> pageResult = new PageResult<>(pageInfo);
        return R.ok(pageResult);
    }

    @Override
    public R<Map> getStockUpDownCount() {

        String stock = DateTimeUtil.getLastDateString4Stock(DateTime.now());
        stock = "20220106092500";
        List<Map> upCont = stockRtInfoMapper.getStockUpDownCount(stock, 1);
        List<Map> downCount = stockRtInfoMapper.getStockUpDownCount(stock, 0);
        HashMap<String, List<Map>> info = new HashMap<>();
        info.put("upList", upCont);
        info.put("downList", downCount);

        return R.ok(info);
    }

    @Override
    public void exportStockExcel(HttpServletResponse response, Integer page, Integer pageSize) {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        try {
            //设置响应数据格式
            response.setContentType("application/vnd.ms-excel");
            //设置编码
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("stockRt", "UTF-8");
            //设置默认文件名称
            response.setHeader("content-disposition", "attachment;filename=" + fileName + ".xlsx");
            //获取导出的分页数据
            PageHelper.startPage(page, pageSize);
            List<Inner> infos = this.stockRtInfoMapper.getStockAll1();
            Gson gson = new Gson();
            List<StockExcelDomain> collect = infos.stream().map(mmm -> {
                StockExcelDomain domain = gson.fromJson(gson.toJsonTree(mmm), StockExcelDomain.class);
                return domain;
            }).collect(Collectors.toList());

            EasyExcel.write(response.getOutputStream(), StockExcelDomain.class).sheet("股票数据").doWrite(collect);
        } catch (IOException e) {
            e.printStackTrace();
            log.info("股票导出异常，当前页：{}，每页大小{}，异常信息{}", page, pageSize, e.getMessage());
        }

    }

    @Override
    public R<Map> getStockTravolCompare() {
        DateTime stock = DateTimeUtil.getLastDate4Stock(DateTime.now());
        String s = DateTimeUtil.parseToString4Stock(stock);
        //TODO 后面注释掉
        s = "20220103143000";
        DateTime dateTime = DateTimeUtil.getPreviousTradingDay(stock);
        String s1 = DateTimeUtil.parseToString4Stock(dateTime);
        s1 = "20220102143000";
        List<Map> maps = stockMarketIndexInfoMapper.getStockTravolCompare(s);
        List<Map> maps1 = stockMarketIndexInfoMapper.getStockTravolCompare(s1);
        HashMap<String, Object> map = new HashMap<>();
        map.put("volList", maps);
        map.put("yesVolList", maps1);

        return R.ok(map);
    }

    @Override
    public R<Map> getStockUpDownScope() {
        //获取最近的有效股票交易时间，精确到分钟
        DateTime target = DateTimeUtil.getLastDate4Stock(DateTime.now());
        String last = DateTimeUtil.getLastDateString4Stock(target);
        // TODO 假数据要删掉的
        last = "20220106095500";
        //查询最近的价格
        List<Map> scope = stockRtInfoMapper.getStockUpDownScope(last);
        List<String> upDownRange = stockInfoConfig.getUpDownRange();
        List<Map> collect = upDownRange.stream().map(kye -> {
            Optional<Map> title = scope.stream().filter(map -> kye.equals(map.get("title"))).findFirst();
            Map map = null;
            if (title.isPresent()) {
                map = title.get();
            } else {
                map = new HashMap();
                map.put("title", kye);
                map.put("count", 0);
                return map;
            }
            return map;
        }).collect(Collectors.toList());


//        ArrayList<Map> maps1 = new ArrayList<>();
//        for (String s : upDownRange) {
//            Map mmm=null;
//            for (Map map : maps) {
//                if (s.equals(map.get("title"))) {
//                    mmm=map;
//                }
//            }
//            if (mmm==null){
//                mmm= new HashMap();
//                mmm.put("title",s);
//                mmm.put("tcount",0);
//            }
//            maps1.add(mmm);
//        }

        Map<String, Object> info = new HashMap<>();
        info.put("time", target.toString("yyyy-MM-dd HH:mm:ss"));
        info.put("infos", collect);
        return R.ok(info);
    }

    @Override
    public R<List<Timesharing>> getStockRtInfoByCode4EvrMinute(String sotckCode) {
        String stock = DateTimeUtil.parseToString4Stock(DateTime.now());
        //TODO 假数据 以后要删掉的
        stock="2022-01-06 13:31:58";
       List<Timesharing>timesharings= stockRtInfoMapper.getStockRtInfoByCode4EvrMinute(stock,sotckCode);
        if (CollectionUtils.isEmpty(timesharings)) {
            return R.error("暂无数据");
        }
        return R.ok(timesharings);
    }

    @Override
    public R<List<Screendkline>> rengetStockRtInfoByCode4EvrMinute(String sotckCode) {
        DateTime days = DateTime.now().minusDays(20);
       String yyyymmdd = days.toString(DateTimeFormat.forPattern("yyyymmdd"));
       yyyymmdd="20211209";
     List<Screendkline>screendklines= stockRtInfoMapper.rengetStockRtInfoByCode4EvrMinute(yyyymmdd,sotckCode);
     if (CollectionUtils.isEmpty(screendklines)){
         return R.error(ResponseCode.SYSTEM_ERROR.getMessage());
     }
        return R.ok(screendklines);
    }

    @Override
    public R<List<Screendkline>> zhougetStockRtInfoByCode4EvrMinute(String sotckCode) {
        DateTime days = DateTime.now().minusDays(20);
        String yyyymmdd = days.toString(DateTimeFormat.forPattern("yyyymmdd"));
        yyyymmdd="20211209";

       List<Screendkline> screendklines= stockRtInfoMapper.zhougetStockRtInfoByCode4EvrMinute(yyyymmdd,sotckCode);
        if (CollectionUtils.isEmpty(screendklines)) {
            return R.error(ResponseCode.SYSTEM_ERROR.getMessage());
        }
        return R.ok(screendklines);
    }
}
